<?php
/**
 * Created by PhpStorm.
 * User: wo
 * Date: 2019/9/18
 * Time: 17:33
 */
class WishApp extends BackendApp
{
    protected $_wish;
    protected $_wishPayLog;
    protected $_wishLog;

    function __construct()
    {
        $this->Banner_settingApp();
    }

    function Banner_settingApp()
    {
        parent::BackendApp();
        $this->_wish = &m('wish');
        $this->_wishLog = &m('wish_log');
        $this->_wishPayLog = &m('wish_pay_log');
    }

    /**心愿单列表*/
    function index(){

        $conditions = $this->_get_query_conditions(array(array(
            'field' => 'state',
            'equal' => '=',
            'type'  => 'numeric',
        ),array(
            'field' => 'wish.add_time',
            'name'  => 'add_time_from',
            'equal' => '>=',
            'handler'=> 'gmstr2time',
        ),array(
            'field' => 'wish.add_time',
            'name'  => 'add_time_to',
            'equal' => '<=',
            'handler'   => 'gmstr2time_end',
        ),array(
            'field' => 'wish.goods_price',
            'name'  => 'goods_price_from',
            'equal' => '>=',
            'type'  => 'numeric',
        ),array(
            'field' => 'wish.goods_price',
            'name'  => 'goods_price_to',
            'equal' => '<=',
            'type'  => 'numeric',
        ),
        ));

        if($_GET['count_from'] || $_GET['count_to']){
            $wishLog = &m('wish_log');

            if($_GET['count_from'] && !$_GET['count_to']){
                $count_from = trim($_GET['count_from']);
                $sql = "select * from (select count(*) as ccaa,wish_id from ecm_wish_log group by wish_id ) as ccaa where ccaa >=$count_from";
            }elseif($_GET['count_to'] && !$_GET['count_from']){
                $count_to = trim($_GET['count_to']);
                $sql = "select * from (select count(*) as ccaa,wish_id from ecm_wish_log group by wish_id ) as ccaa where ccaa <=$count_to";
            }else{
                $count_to = trim($_GET['count_to']);
                $count_from = trim($_GET['count_from']);
                $sql = "select * from (select count(*) as ccaa,wish_id from ecm_wish_log group by wish_id ) as ccaa where (ccaa >=$count_from and ccaa<=$count_to)";
            }
            $info = $wishLog->db->query($sql);
            while ($chat = $wishLog->db->fetchRow($info)) {
                $chat_listOld[] = $chat;
            }
            if(!empty($chat_listOld)){
                $wish_ids = '';
                foreach($chat_listOld as $k=>$v){
                    if($k == 0){
                        $wish_ids = $v['wish_id'];
                    }else{
                        $wish_ids .= ','.$v['wish_id'];
                    }
                }
                $conditions .= " AND id in (".$wish_ids.")";
            }
            $this->assign('count_from',$_GET['count_from']);
            $this->assign('count_to',$_GET['count_to']);
        }

        //国际码搜索
        if($_GET['international_code']){
            $goodsSpec = & m('goodsspec');
            $conditions = ' AND gs.international_code like '."'%".trim($_GET['international_code'])."%'";
            $this->assign('international_code',$_GET['international_code']);
        }
        //用户名搜索
        if($_GET['user_name']){
            $member = & m('member');
            $conditions = ' AND member.user_name like '."'%".trim($_GET['user_name'])."%'";
            $this->assign('user_name',$_GET['user_name']);
        }
        $page = $this->_get_page(10);
        $res = $this->_wish->find(array(
            'fields' => 'wish.*,member.user_name,goods.goods_name,goodsspec.spec_1value,goodsspec.spec_2,goodsspec.spec_1,goodsspec.sku',
            'join' => 'has_member,has_goods,has_goods_spec',
            'conditions'    => '1=1 ' . $conditions,
            'limit' => $page['limit'],
            'count' => true,
            'order' => "add_time desc"
        ));
        foreach($res as $j=>$v){
            //首款
            $res[$j]['first_paragraph'] = $this->_wishPayLog->getPayLog($v['id'],1);
            //尾款
            $res[$j]['last_paragraph'] = $this->_wishPayLog->getPayLog($v['id'],2);
            //后台补交金额
            $res[$j]['help_paragraph'] = $this->_wishPayLog->getPayLog($v['id'],3);
            //邀请人砍价金额
            $res[$j]['chop_paragraph'] = $this->_wishLog->getInvalid($v['id']);
            //邀请人数
            $res[$j]['count'] = $this->_wishLog->getCounts($v['id']);
            $res[$j]['spec_1'] = WEB_PHOTO_SRC.'/'.$v['spec_1'];
        }
        $page['item_count'] = $this->_wish->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('res', $res);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $page['item_count'] = $this->_wish->getCount();
        $this->assign('wish_state_list', array(
            0  =>  Lang::get('wish_cancel'),
            1     =>  Lang::get('wish_ing'),
            2  =>  Lang::get('wish_finish'),
            3 =>  Lang::get('wish_invalid'),
            4 =>  Lang::get('wish_out'),
        ));
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->display('wish.index.html');
    }

    /***查看付款记录*/
    function view_pay_log(){
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $conditions = 'wish_id = '.$id;
        $page = $this->_get_page(10);
        $res = $this->_wishPayLog->find(array(
            'fields'  => 'wish_pay_log.*,member.user_name',
            'join'     =>  'has_member',
            'conditions'    =>  $conditions,
            'limit' => $page['limit'],
            'count' => true,
        )); //找出所有商城的合作伙伴
        $page['item_count'] = $this->_wishPayLog->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('res', $res);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $page['item_count'] = $this->_wishPayLog->getCount();
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->display('wish.pay_log.html');
    }

    /***查看砍价记录**/
    function view_log(){
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $conditions = 'wish_id = '.$id;
        $page = $this->_get_page(10);
        $res = $this->_wishLog->find(array(
            'fields'  => 'wish_log.*,member.user_name',
            'join'    =>  'has_member',
            'conditions'    =>$conditions,
            'limit' => $page['limit'],
            'count' => true,
        )); //找出所有商城的合作伙伴
        $member = &m('member');
        foreach($res as $k=>$v){
            $memberInfo = $member->get(array(
                'conditions' => 'user_id ='.$v['inviter_id'],
                'fields'     => 'user_name',
            ));
            $res[$k]['people_name'] = $memberInfo['user_name'];
        }
        $page['item_count'] = $this->_wishLog->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('res', $res);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $page['item_count'] = $this->_wishLog->getCount();
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->display('wish.log.html');
    }

    //后台帮砍
    function amount_money(){
        $id = $_GET['wish_id'];
        if(!$id){
            $this->show_warning('no_such_param');
            return;
        }
        $info = $this->_wish->get(array(
            'conditions'  =>  'id = '.$id
        ));


        $conditions = 'wish.spec_id = '.$info['spec_id'];
        $conditions .= ' AND wish.id = '.$id;
        //查询匹配的规格信息
        $goodsSpecInfo = $this->_wish->get(array(
            'fields'  => 'gs.*',
            'join'     =>  'has_goods_spec',
            'conditions'    =>  $conditions,
            'count' => true,
        ));

        //所购买商品库存不足，向用户发起退款，并取消心愿单
        if($goodsSpecInfo['stock'] < 1){
            //查看该笔心愿单支付记录
            $wishPayInfo = $this->_wishPayLog->get(array('conditions'=>"wish_id = ".$id));
            $wishRefundResult = $this->refundWishPalyLog($wishPayInfo);
            //执行微信退款流程
            $time = time();
            $saveData = array(
                'state' => 4,
                'finish_time' => $time,
                'msg' => '用户所购买的商品库存不足，已售罄，系统自动判定已取消心愿单，并进行退款',
            );
            if($wishPayInfo['pay_type'] == 1){
                if($wishRefundResult['result_code'] == 'SUCCESS' && $wishRefundResult['return_code'] == 'SUCCESS'){
                    $this->_wish->edit($id,$saveData);
                }else{
                    $this->show_warning('微信退款失败'.$wishRefundResult['return_msg']);
                    return;
                }
            }else{
                //支付宝
                if($wishRefundResult['code'] == '10000'){
                    $this->_wish->edit($id,$saveData);
                }else{
                    $this->show_warning('微信退款失败'.$wishRefundResult['return_msg']);
                    return;
                }
            }
            $this->show_warning('用户所购买的商品库存不足，系统自动判定已取消心愿单，并进行退款');
            return;
        }
        //生成订单
        $wishResult = $this->_wish->createOrder($id);
        if($wishResult['code'] == 1){
            $this->show_message('操作成功',
                'back_list',        'index.php?app=wish',
                'edit_again',    'index.php?app=wish&amp;act=index&amp;id=' . $id);
        }else{
            $this->show_warning('操作失败',
                'back_list',        'index.php?app=wish',
                'edit_again',    'index.php?app=wish&amp;act=index&amp;id=' . $id);
        }

    }

    //库存不足进行退款
    function refundWishPalyLog($wishPayInfo){
        ini_set('display_errors','on');
        error_reporting(E_ALL);
        $out_trade_no = $wishPayInfo["order_sn"];
        $total_fee = $wishPayInfo["money"] * 100;
        $refund_fee = $wishPayInfo["money"] * 100;
        $refund_alifee = $wishPayInfo["money"];
        if($wishPayInfo['pay_type'] == 1){
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Data.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Api.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Config.php";
            $input = new WxPayRefund();
            $input->SetOut_trade_no($out_trade_no);
            $input->SetTotal_fee($total_fee);
            $input->SetRefund_fee($refund_fee);
            $config = new WxPay1Config();
            $input->SetOut_refund_no($wishPayInfo['trade_no']);
            $rs = WxPay1Api::refund($config,$input, 60);
            return $rs;
        }else if($wishPayInfo['pay_type'] == 2) {
            $config = include_once ROOT_PATH . "/includes/payments/epayalipay/epayalipayrefund/config.php";
            include_once ROOT_PATH . "/includes/payments/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
            include_once ROOT_PATH . "/includes/payments/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($out_trade_no);
            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($refund_alifee);
            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//                $out_request_no = trim($_POST['WIDTRout_request_no']);
            //构造参数
            $RequestBuilder = new AlipayTradeRefundContentBuilder();
            $RequestBuilder->setOutTradeNo($out_trade_no);
            $RequestBuilder->setRefundAmount($refund_amount);
            $aop = new AlipayTradeService($config, true);
            $response = $aop->RefundJson($RequestBuilder);
            $rs = json_decode(json_encode($response), true);
            return $rs;
        }
    }

}